<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chat with DeepSeek-V3</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        background-color: #f4f4f4;
        margin: 0;
        padding: 0;
      }
      .chat-container {
        width: 100%;
        max-width: 400px;
        margin: 20px auto;
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        overflow: hidden;
      }
      .chat-box {
        height: 400px;
        overflow-y: auto;
        padding: 15px;
        background: #f9f9f9;
        border-bottom: 1px solid #ddd;
      }
      .chat-box .message {
        margin-bottom: 10px;
        padding: 5px 10px;
        background: #e1f5fe;
        border-radius: 5px;
        white-space: pre-wrap; /* 添加这行 */
      }
      .chat-box .message.user {
        background: #d1f7d9;
      }
      .input-container {
        display: flex;
        padding: 10px;
      }
      .input-container input[type="text"] {
        flex: 1;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
        margin-right: 10px;
      }
      .input-container button {
        padding: 10px 20px;
        background: #007bff;
        color: #fff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
      }
      .input-container button:hover {
        background: #0056b3;
      }
    </style>
  </head>
  <body>
    <div class="chat-container">
      <div class="chat-box" id="chatBox"></div>
      <div class="input-container">
        <input
          type="text"
          id="messageInput"
          placeholder="Type your message here..."
        />
        <button id="sendButton">Send</button>
      </div>
    </div>

    <script>
      const chatBox = document.getElementById("chatBox");
      const messageInput = document.getElementById("messageInput");
      const sendButton = document.getElementById("sendButton");

      sendButton.addEventListener("click", sendMessage);
      messageInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
          sendMessage();
        }
      });

      function sendMessage() {
        const message = messageInput.value.trim();
        if (message === "") return;

        // Display user's message
        const userMessageElement = document.createElement("div");
        userMessageElement.classList.add("message", "user");
        userMessageElement.textContent = message;
        chatBox.appendChild(userMessageElement);

        // Scroll to the bottom
        chatBox.scrollTop = chatBox.scrollHeight;

        // Clear input
        messageInput.value = "";

        // Send message to API and get response
        fetchResponse(message);
      }
      async function readStream(stream) {
        const reader = stream.getReader(); // 获取流的读取器
        const decoder = new TextDecoder(); // 用于将字节流解码为文本
        let result = "";

        while (true) {
          const { done, value } = await reader.read(); // 异步读取流
          if (done) {
            console.log("Stream reading done.");
            break;
          }
          result += decoder.decode(value, { stream: true }); // 解码并拼接数据
          console.log("Stream data:", result);
        }
        console.log("Final result:", result);
      }
      let history = [];
      history.push({
        role: "system",
        content: "你是一个超级写手，可以把用户提供的任何内容变成一段网文",
      });
      async function fetchResponse(userMessage) {
        history.push({
          role: "user",
          content: userMessage,
        });
        const token = "sk-hsoftbtfpjmeyjrnsxxnlzzahqrsgglqonwozffdbgjsvszu";
        const url = "https://api.siliconflow.cn/v1/chat/completions"; // 替换为实际的API URL
        const payload = {
          model: "deepseek-ai/DeepSeek-V3",
          messages: history,
          stream: true,
          max_tokens: 512,
          temperature: 0.7,
          top_p: 0.7,
          top_k: 50,
          frequency_penalty: 0.5,
          n: 1,
          response_format: { type: "text" },
        };

        const headers = {
          Authorization: `Bearer ${token}`, // 替换为您的API密钥
          "Content-Type": "application/json",
        };

        let response = await fetch(url, {
          method: "POST",
          headers: headers,
          body: JSON.stringify(payload),
        });
        console.log('response',response)
        if(response.status != 200){
          const botMessageElement = document.createElement("div");
          botMessageElement.classList.add("message");
          chatBox.appendChild(botMessageElement);
          chatBox.scrollTop = chatBox.scrollHeight;
          botMessageElement.textContent = response.message;
          return
        }
        // response.json();
        // readStream(response.body);
        if (!payload.stream) {
          let data = await response.json();
          console.log(data);
          let botMessage = data.choices[0].message.content.trim();
          console.log(botMessage);
          const botMessageElement = document.createElement("div");
          botMessageElement.classList.add("message");
          chatBox.appendChild(botMessageElement);
          chatBox.scrollTop = chatBox.scrollHeight;
          botMessageElement.textContent = `Bot: ${botMessage}`;
          return;
        }
        // let words = [];
        const botMessageElement = document.createElement("div");
        botMessageElement.classList.add("message");
        chatBox.appendChild(botMessageElement);
        chatBox.scrollTop = chatBox.scrollHeight;

        let stream = response.body;
        const reader = stream.getReader(); // 获取流的读取器
        const decoder = new TextDecoder(); // 用于将字节流解码为文本
        let result = "";
        botMessageElement.textContent = `思考中...`;

        while (true) {
          const { done, value } = await reader.read(); // 异步读取流
          if (done) {
            console.log("Stream reading done.");
            break;
          }
          let decodedData = decoder.decode(value, { stream: true });
          // console.log('decodedData', `[${decodedData}]` );
          if (decodedData.startsWith("data: [DONE]")) {
            console.log("结束！");
            break;
          }
          let textobjs = decodedData.match("data: (.*)\n");
          let str = "";
          // console.log('textobjs',textobjs)
          // textobjs.forEach((text) => {
          // })
          let text = textobjs[1];
          if (text.startsWith("data: ")) {
            text = text.substring(6);
          }
          let obj = JSON.parse(text);
          let content = obj.choices[0].delta.content;
          str += content;
          console.log("content", content);
          // let obj = JSON.parse(str);
          result += str; // 解码并拼接数据
          botMessageElement.textContent = `Bot: ${result}`;
          chatBox.scrollTop = chatBox.scrollHeight;
        }
        console.log("Final result:", result);
        history.push({
          role: "assistant",
          content: result,
        });
        // .then((data) => {
        //   console.log("data", data);
        //   const botMessage = data.choices[0].message.content.trim();
        //   const botMessageElement = document.createElement("div");
        //   botMessageElement.classList.add("message");
        //   botMessageElement.textContent = `Bot: ${botMessage}`;
        //   chatBox.appendChild(botMessageElement);
        //   chatBox.scrollTop = chatBox.scrollHeight;
        // })
        // .catch((error) => {
        //   const errorMessageElement = document.createElement("div");
        //   errorMessageElement.classList.add("message");
        //   errorMessageElement.textContent = `Error: ${error.message}`;
        //   chatBox.appendChild(errorMessageElement);
        //   chatBox.scrollTop = chatBox.scrollHeight;
        // });
      }
    </script>
  </body>
</html>
